package com.wjd.wshow.util;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Random;

public class ResourceUtil {

    private static int thumbStart = 30;
    private static int thumbEnd = 100;
    private static Random random = new Random();

    private ResourceUtil() {}

    /**
     * 生成视频缩略图
     * @param videoPath 视频路径
     * @param framePath 缩略图路径
     * @throws Exception 生成失败时抛出异常
     */
    public static void frameThumbnail(String videoPath, String framePath) throws Exception {
        File targetFile = new File(framePath);
        if (targetFile.exists()) {
            FileUtils.forceDelete(targetFile);
        }

        // 获取视频
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videoPath);
        ff.start();
        int length = ff.getLengthInFrames();
        if (length <= 0) {
            return;
        }

        // 跳过帧数，避免出现全黑的图片
        int skip = random.nextInt(thumbEnd - thumbStart) + thumbStart;
        Frame f = ff.grabImage();
        Frame frame = f;
        for (int i = 1; i < skip && i < length; i++) {
            f = ff.grabImage();
            if (f != null) {
                frame = f;
            }
        }

        // 生成缩略图
        BufferedImage frameImage = frameToBufferedImage(frame);
        Thumbnails.of(frameImage).size(240, 240).toFile(targetFile);
        ff.stop();
    }

    /**
     * 利用视频帧生成图片
     * @param frame 视频帧
     * @return 图片
     */
    private static BufferedImage frameToBufferedImage(Frame frame) {
        BufferedImage bufferedImage;
        Java2DFrameConverter converter = new Java2DFrameConverter();
        bufferedImage = converter.getBufferedImage(frame);
        return bufferedImage;
    }
}
